//
//  SYDownloadVideo.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/29.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import Alamofire

class SYDownloadVideo: NSObject {
    var downloadRequest:DownloadRequest!
    
    func downloadVideo(url: String, closure: @escaping (URL?) -> Void) {
        HUDUtil.showHud()
        if let u = URL(string: url) {
            let urlRequest = URLRequest(url: u)
            
            downloadRequest = AF.download(urlRequest as URLRequestConvertible)
            downloadRequest.downloadProgress(closure: downloadProgress)
            downloadRequest.responseData { (response) in
                HUDUtil.hideHud()
                switch response.result {
                case .success(_):
                    //下载完成
                    DispatchQueue.main.async {
                        let path: String = response.fileURL?.path ?? ""
                        print("路径:\(path)")
                        closure(response.fileURL)
                    }
                case .failure(error:):
                    //                        self.cancelledData = response.resumeData //意外中止的话把已下载的数据存起来
                    HUDUtil.showBlackTextView(text: "下载图片失败")
                    break
                }
            }
        }
        
    }
    
    func downloadProgress(progress:Progress){
        
//        print("当前下载video进度:\(progress.fractionCompleted*100)%")
    }
    
    func cancel() {
        downloadRequest.cancel()
    }
}
